package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.oa.core.entity.com.Expense;
import com.fz.us.oa.core.entity.com.Pay;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.PayService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 控制器 - 财务模块-付款申请
 * ============================================================================
 * 版权所有 2016 。
 *
 * @version 1.0 2016-12-28 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/com/pay")
public class PayController extends BaseController {


    private static final long serialVersionUID = 589183935496478507L;
    @Autowired
    private PayService payService;



    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> payTypeDict = getDictItems(user,"payType");
        if (StringUtils.isNotEmpty(keyId)){
            Pay pay = payService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("pay", pay);
        }
        model.addAttribute("payTypeDict", payTypeDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/pay_input";
    }



    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> payTypeDict = getDictItems(user,"payType");
        if(StringUtils.isNotEmpty(keyId)) {
            Pay pay = payService.get(keyId);
            String userEdit =  userEdit(keyId);
            model.addAttribute("pay", pay);
            model.addAttribute("userEdit", userEdit);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("payTypeDict", payTypeDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/pay_read";
    }

    /**
     * 赋值数据
     */
    private Pay setData(User user, String keyId,  String typeDictId,
                         String amount,String payDate,String object, String bank, String account){
        Pay pay = null;
        if(StringUtils.isNotEmpty(keyId)){
            pay = payService.get(keyId);
        }else{
            pay = new Pay();
            pay.setCreater(user);
        }
        pay.setType(dictItemService.get(typeDictId));
        pay.setAmount(new BigDecimal(amount));
        pay.setPayDate(DataUtil.StringToDate(payDate));
        pay.setObject(object);
        pay.setBank(bank);
        pay.setAccount(account);
        pay.setCompany(user.getCompany());
        return pay;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,  String keyId,  String typeDictId,
                       String amount,String payDate,String object, String bank, String account) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Pay pay = setData( user, keyId, typeDictId, amount, payDate, object, bank, account);
        if(StringUtils.isNotEmpty(keyId)){
            payService.update(pay);
            rMap.put("message", "更新成功");
        } else {
            payService.save(pay, "com.fz.us.oa.core.entity.com.Pay");
            rMap.put("message","保存成功");
        }
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }


    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId,  String typeDictId,
                         String amount,String payDate,String object, String bank, String account, String comment, String next, String editorsId, String remindUserId){
        User editor = null;
        if(StringUtils.isNotEmpty(editorsId)){
            editor = userService.get(editorsId);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        Pay pay = setData( user, keyId, typeDictId, amount, payDate, object, bank, account);

        if (StringUtils.isNotEmpty(keyId)) {
            payService.approve(pay, user, comment, next, editor);
        } else {
            keyId=payService.commit(pay,"com.fz.us.oa.core.entity.com.Pay", user, next, editor);
        }
        toRemind("pay", keyId, remindUserId,user.getName()+"提交的付款申请表，请查看");
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String comment, String next, String editorsId, String remindUserId){
        User editor = null;
        if(StringUtils.isNotEmpty(editorsId)){
            editor = userService.get(editorsId);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        Pay pay = payService.get(keyId);
        payService.approve(pay, user, comment, next, editor);
        toRemind("pay", keyId, remindUserId, user.getName() + "提交的付款申请表，请查看");
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String backStepNo, String comment, String remindUserId) {
        if (StringUtils.isNotEmpty(keyId)) {
            Pay pay = payService.get(keyId);
            if(StringUtils.isNotEmpty(backStepNo)){
                String[] arr = backStepNo.split("\\|");
                int stepNo = Integer.parseInt(arr[0]);
                User editor = userService.get(arr[1]);
                payService.back(pay, comment, stepNo, editor);
                toRemind("pay", keyId, remindUserId, user.getName() + "退回的付款申请表，请查看");
            }
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId, String comment, String remindUserId) {
        if (StringUtils.isNotEmpty(keyId)) {
            Pay pay = payService.get(keyId);
            payService.deny(pay, comment);
            toRemind("pay", keyId, remindUserId, user.getName() + "否决的付款申请表，请查看");
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                     String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;
        if(viewtype !=null && viewtype.equals("2")){
            order = Order.order("modifyTime", SearchEnum.OrderType.desc);
        }
        SearchResultPaging searchResult = null;
       // List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //申请中
                searchResult = payService.paging(order,
                        "com.fz.us.oa.core.entity.com.Pay", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //已通过
                searchResult =  payService.paging(order,
                        "com.fz.us.oa.core.entity.com.Pay", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //已否决
                searchResult =  payService.paging(order,
                        "com.fz.us.oa.core.entity.com.Pay", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Deny}, params);
            }
        }else{
            //所有单子
            searchResult = payService.paging(order,
                    "com.fz.us.oa.core.entity.com.Pay",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }
        List<Pay> payList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Pay pay: payList){
                TaskEntity taskEntity = taskEntityService.getInfoByKeyId(pay.getId());
                Set<User> users = taskEntity.getEditors();
                String editor = "";
                for(User editorName:users){
                    editor += editorName.getName()+",";
                }
                if(StringUtils.isNotEmpty(editor)){
                    editor = editor.substring(0, editor.length()-1);
                }
                rMap = new HashMap<String, Object>();
                rMap.put("id",pay.getId());
                rMap.put("type",pay.getType() != null?pay.getType().getName():"");
                rMap.put("amount",pay.getAmount()!= null? pay.getAmount().toString():"");
                rMap.put("creater", pay.getCreater() != null ? pay.getCreater().getName() : "");
                rMap.put("createTime", DataUtil.DateToString(pay.getCreateTime(),"yyyy-MM-dd"));
                rMap.put("modifyTime", DataUtil.DateToString(pay.getModifyTime(),"yyyy-MM-dd"));
                rMap.put("payDate", DataUtil.DateToString( pay.getPayDate(),"yyyy-MM-dd"));
                rMap.put("object",pay.getObject());
                rMap.put("editor", editor);
                rMap.put("state",pay.getProcessState().value());
                dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }



}
